<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { marked } from "marked";
import { Create } from "../api/conversation.js";
import { GetRealtimeMessage } from "../api/chat.js";

let map = null;

const conversationId = ref("");
const queryContent = ref("");
const resultContent = ref("");
let marker = null;

onMounted(() => {
  AMapLoader.load({
    key: "bb950c069f81442cf67bf150a32c3f61", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  })
    .then((AMap) => {
      map = new AMap.Map("map_container", {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 11, // 初始化地图级别
        center: [120.579712, 31.296423], // 初始化地图中心点位置
      });
      map.on("click", handleMapClick);
    })
    .catch((e) => {
      console.log(e);
    });
});

const handleMapClick = (e) => {
  console.log("map", map);
  if (marker) {
    marker.setMap(null);
    marker = null;
  }
  console.log("handleMapClick", e);
  console.log(e.lnglat.lng + "," + e.lnglat.lat);
  marker = new AMap.Marker({
    position: new AMap.LngLat(e.lnglat.lng, e.lnglat.lat), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
    title: "",
  });
  map.add(marker);
  queryContent.value = e.lnglat.lng + "," + e.lnglat.lat;
};

onUnmounted(() => {
  map?.destroy();
});

const handleCreateClick = () => {
  Create().then((result) => {
    console.log("chat", result.data.data.id);
    conversationId.value = result.data.data.id;
  });
};

const getMessage = (message) => {
  let resultData = JSON.parse(message.data);

  //console.log(resultData.content, resultData);
  if (
    resultData.content &&
    resultData.type == "answer" &&
    message.event == "conversation.message.delta"
  ) {
    console.log(resultData.content);
    resultContent.value += resultData.content;
  }
};

const handleChatClick = () => {
  resultContent.value = "";
  GetRealtimeMessage(conversationId.value, queryContent.value, getMessage);
};
</script>

<template>

  <div id="container">
    <div id="result_container" v-html="marked(resultContent)"></div>
    <div id="map_container"></div>
    <div id="button-container">  <button @click="handleCreateClick()">创建对话</button>
      <button @click="handleChatClick()">获取推荐</button></div>
  </div>
</template>

<style scoped>
#container {
  width: 100vw;
  height: 100vh;
  display: flex;
}
#result_container {
  display: inline-block;
  width: 30vw;
  height: calc(100vh - 40px);
  padding: 10px;

  /* white-space: pre-line; */
}
#map_container {
  display: inline-block;
  width: 70vw;
  height: 100vh;
}
#button-container{
  position: fixed;
  right: 20px;
  top:20px
}
</style>
